package mobile

import (
	"net/http"
	"strconv"

	"gitee.com/cxssang/goframe/lib/utils"

	"gitee.com/cxssang/goframe/lib/sql"

	. "gitee.com/cxssang/genealogy/act"
)

func init() {
	HandleFunMap["/m/me"] = func(w http.ResponseWriter, r *http.Request) {
		id := r.Header.Get("member-id")
		user, err := sql.Raw("select a.*,b.name parent_name from members a left join members b on(b.id=a.parent_id) where a.id=? limit 1").SetParams(id).FetchOne()
		if err != nil {
			DisplayError(w, err.Error())
			return
		}
		if user == nil {
			DisplayError(w, "用户不存在")
			return
		}
		user.Set("sex", SexMap2[user.Get("sex")])
		DisplayM(w, r, "mobile/me", map[string]interface{}{
			"user":  user,
			"title": "我 - 族谱管理",
		})
	}

	HandleFunMap["/m/profile"] = func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "POST" {
			fieldName := r.FormValue("field")
			value := r.FormValue("value")
			if fieldName == "" {
				JsonError(w, "缺少参数")
				return
			}
			data := map[string]interface{}{}
			if fieldName == "password" {
				value = utils.Md5(value)
			}
			data[fieldName] = value
			_, err := sql.New().Update("members", sql.NewWhere().Add("id=?", r.Header.Get("member-id")), data).Exec()
			if err != nil {
				JsonError(w, err.Error())
			} else {
				JsonSuccess(w, nil)
			}
		}
	}

	HandleFunMap["/m/me/tree"] = func(w http.ResponseWriter, r *http.Request) {
		sq := sql.New()
		rows, err := sq.Select("members", sql.NewWhere(), 0, 0, "id,name,spouse,sex,birth,parent_id,sort", "sort asc").FetchAll()
		if err != nil {
			DisplayError(w, err.Error())
			return
		}
		if rows == nil {
			rows = sql.Rows{}
		}

		var nodes []*Node
		for _, row := range rows {
			node := &Node{
				ID:       row.GetInt("id"),
				Name:     row.Get("name"),
				ParentID: row.GetInt("parent_id"),
				Spouse:   row.Get("spouse"),
				Sex:      row.Get("sex"),
				Birth:    row.Get("birth"),
				Sort:     row.GetInt("sort"),
			}
			nodes = append(nodes, node)
		}
		id, _ := strconv.Atoi(r.Header.Get("member-id"))
		user, _ := sq.Select("members", sql.NewWhere().Add("id=?", id), 0, 0, "spouse", "").FetchOne()
		tree := BuildTree(nodes, id)
		tree = []*Node{
			{
				ID:       id,
				Name:     "我",
				Children: tree,
				ParentID: 0,
				Spouse:   user.Get("spouse"),
			},
		}

		DisplayM(w, r, "mobile/tree", map[string]interface{}{
			"title": "后代关系图 - 族谱管理",
			"tree":  CreateTree(tree),
			"m":     true,
		})
	}
}
